<template>
  <div class="app-container">
    <el-button type="primary" v-if="$unit.isPower('create roles')" @click="handleAddRole">添加角色</el-button>

    <el-table stripe :data="permissionList" style="width: 100%; margin-top: 10px" border>
      <el-table-column align="center" width="100px" label="小组编号">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <el-table-column align="center" width="200px" label="角色名称">
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column align="center" label="权限配置">
        <template slot-scope="scope">
          <div v-for="(item, index) in scope.row.perArr" :key="index" style=" text-align: center;  padding: 3px; border-radius: 7px;  font-size: 10px; color: #fff; margin: 1px; background: cornflowerblue;  white-space: normal; word-break: break-all;  float: left; ">
            {{ item }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" width="200" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" v-if="$unit.isPower('update roles')" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" v-if="$unit.isPower('delete roles')" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination ref="pager" background :current-page="pageIndex" :page-size="pageSize" :total="total" layout="prev, pager, next" @size-change="sizeChangeHandle" @current-change="currentChangeHandle" />
    </div>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType === '添加角色' ? '添加角色' : '权限配置'">
      <el-form :model="permission" label-width="80px" label-position="left">
        <el-form-item label="角色名称 *">
          <el-input v-model="permission.name" placeholder="请输入权限名称" />
        </el-form-item>

        <el-form-item label="权限说明 *" class="label_per">

          <!-- <div v-for="(perList, l_index) in classifys" :key="l_index"> -->
          <div v-for="(perList, l_index) in classifys" :key="l_index">
            {{ perList.title }}
            <ul v-for="(item, index) in perList.classify_has_many" :key="index">
              <el-checkbox v-model="item.checked" :indeterminate="item.isIndeterminate" @change="handleCheckAllChange($event, l_index,index)">{{ item.title }}</el-checkbox>

              <li>
                <el-checkbox v-for="(name, i) in item.has_many_details" :key="i" v-model="name.checked" :label="name.has_details.explain" @change="
                  handleCheckedCitiesChange(
                    l_index,
                    index,
                    i,
                    name.has_details.id,
                    $event
                  )
                ">{{ name.has_details.explain }}</el-checkbox>
              </li>
            </ul>
          </div>
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button type="danger" @click="cancelRole">取消</el-button>
        <el-button type="primary" @click="confirmRole">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getInfo } from '@/api/user'
import {
  getClassify,
  getClassifyPermissions,
  deleteClassifyPermissions,
  getClassifyPermissionsPage,
  insertClassifyPermissions,
  updateClassifyPermissions
} from '@/api/classify'
// import { getClassify } from "@/api/classify";

export default {
  name: 'PagePermission',
  components: {},
  data() {
    return {
      permissionList: [], // 权限数据数组
      pageIndex: 1, // 第几页
      pageSize: 2, // 一页数量
      total: 0, // 总页数
      dialogVisible: false, // dialog显示隐藏
      dialogType: '', // dialog的标题
      permission: {
        name: '',
        instructions: '',
        roles: []
      }, // 权限
      classify: '', // 角色
      perId: '', // 编辑单个id 变量
      arr: [],
      perList: [],
      classifys: [],
      checkedList: [],
      userPermissions: '', // 用户权限数组
      checkAll: false,
      checkList: [],
      checkedAllList: [], // 默认选中
      childrenArrayHead: [],
      childrenArray: []
    }
  },
  created() {
    this.selectClassifyPermissions()
  },
  methods: {
    // 判断是否具有某某权限
    isPower(Permission) {
      for (let i = 0; i < this.userPermissions.length; i++) {
        if (this.userPermissions[i] == Permission) {
          return true
        }
      }
      return false
    },
    handleCheckAllChange(e, l_index, index) {
      const childrenArray = this.classifys[l_index].classify_has_many[index] // 当前属于哪一个权限分类
      // console.log(e)

      childrenArray.checked = e
      childrenArray.isIndeterminate = e 
      childrenArray.isIndeterminate = !e 
      this.childrenArrayHead = childrenArray.has_many_details
      var len = this.childrenArrayHead.length
      for (var c_index in this.childrenArrayHead) {
        // this.childrenArrayHead[index].checked = e
        this.classifys[l_index].classify_has_many[index].has_many_details[c_index].checked = e
      }

       childrenArray.isIndeterminate = false



    },
    handleCheckedCitiesChange(l_index, index, i, sobId, e) {
      const childrenArray = this.classifys[l_index].classify_has_many[index] // 当前属于哪一个权限分类
      var len = childrenArray.has_many_details.length
      childrenArray.has_many_details[i].checked = e


      this.$set(this.classifys[l_index].classify_has_many, index, childrenArray)

      var checkNum = 0;
      childrenArray.has_many_details.forEach(element => {
        if (element.checked == true) {
          checkNum++;
        }
      });

      if (checkNum == len) {
        this.classifys[l_index].classify_has_many[index].isIndeterminate = false
        this.classifys[l_index].classify_has_many[index].checked = true
      } else {
        this.classifys[l_index].classify_has_many[index].isIndeterminate = false
        this.classifys[l_index].classify_has_many[index].checked = false
      }

    },

    // 下一页
    sizeChangeHandle: function (size) {
      this.pagesize = size
    },
    currentChangeHandle: function (val) {
      return new Promise((resolve, reject) => {
        getClassifyPermissionsPage(val).then(response => {
          // 调用分页方法 下一页 查询
          this.permissionList = response.data.roles.data
          this.perList = response.data.classify[0].classify_has_many

          this.classifys = response.data.classify
          // 第一层for循环 获取有多少个角色
          for (let i = 0; i < this.permissionList.length; i++) {
            // 循环完一个角色后 将权限配置数组设置为空
            this.arr = []
            // 第二层for循环 获取当前角色拥有那些权限
            for (
              let j = 0;
              j < this.permissionList[i].has_many_details.length;
              j++
            ) {
              // 第三层for循环 获取当前数据库中拥有的所有的权限
              for (let k = 0; k < response.data.Permissions.length; k++) {
                // 判断当前角色拥有的权限 id 和 数据库的权限id 相同时 将 当前权限的名字 放进arr 数组中
                if (
                  this.permissionList[i].has_many_details[j].id ==
                  response.data.Permissions[k].id
                ) {
                  this.arr.push(
                    response.data.Permissions[k].has_details.explain
                  )
                  // 将数组转换成字符串 展示到页面中
                  this.permissionList[i].perArr = this.arr
                }
              }
            }
          }
        })
      })
    },
    // 查询列表
    selectClassifyPermissions() {
      new Promise((resolve, reject) => {
        getClassifyPermissions().then(response => {
          // 获取数据显示
          // 将后台拿到的数据转换
          this.permissionList = response.data.roles.data // 查询到的所有角色信息

          this.perList = response.data.classify[0].classify_has_many // 现有的全部的权限
          this.classifys = response.data.classify

          this.total = response.data.roles.total
          this.pageSize = response.data.roles.to
          // console.log(this.perList);
          // 第一层for循环 获取有多少个角色
          for (let i = 0; i < this.permissionList.length; i++) {
            // 循环完一个角色后 将权限配置数组设置为空
            this.arr = []
            // 第二层for循环 获取当前角色拥有那些权限
            for (
              let j = 0;
              j < this.permissionList[i].has_many_details.length;
              j++
            ) {
              // 第三层for循环 获取当前数据库中拥有的所有的权限
              for (let k = 0; k < response.data.Permissions.length; k++) {
                // 判断当前角色拥有的权限 id 和 数据库的权限id 相同时 将 当前权限的名字 放进arr 数组中
                if (
                  this.permissionList[i].has_many_details[j].id ==
                  response.data.Permissions[k].id
                ) {
                  this.arr.push(
                    response.data.Permissions[k].has_details.explain
                  )
                  // 将数组转换成字符串 展示到页面中
                  this.permissionList[i].perArr = this.arr
                  this.permissionList[i].perArrId =
                    response.data.Permissions[k].id
                }
              }
            }
          }
          // console.log(this.permissionList);
        })
      })
    },

    // 添加角色按钮
    handleAddRole() {
      this.dialogType = '添加角色'
      this.dialogVisible = true
      // 打开dialog框后查询角色内容 填充到select框中
      new Promise((resolve, reject) => {
        getClassify().then(response => {
          // 填充数据
          this.classify = response.data
        })
      })
    },

    // 提交dialog框
    confirmRole() {
      if (this.dialogType == '添加角色') {
        // console.log(this.permission.name);
        // console.log(this.childrenArrayHead);
        // console.log(this.perList);
        // 添加角色 请求
        new Promise((resolve, rejetc) => {
          insertClassifyPermissions({
            name: this.permission.name,
            classifys: this.classifys
          }).then(response => {
            this.$message({
              type: 'success',
              message: '角色添加成功'
            })
            // 添加权限成功后清除表单输入框内容
            this.permission.name = ''
            this.permission.instructions = ''
            this.permission.roles = ''
            this.classifys = ''
            // 关闭dialog框
            this.dialogVisible = false
            for (let i = 0; i < this.classifys.length; i++) {
              // console.log("66");
              // console.log(this.perList[i]);
              this.classifys[i].checked = false
              this.classifys[i].isIndeterminate = true
              for (
                let j = 0;
                j < this.classifys[i].has_many_details.length;
                j++
              ) {
                // console.log(
                //   this.classifys[i].has_many_details[j].has_details.explain
                // );
                this.classifys[i].has_many_details[j].checked = false
              }
            }
            this.selectClassifyPermissions()
            // this.pageIndex = 1;
          })
        })
      } else {
        // console.log(this.perList);
        // 编辑权限信息 请求
        new Promise((resolve, reject) => {
          updateClassifyPermissions({
            id: this.perId,
            name: this.permission.name,
            classifys: this.classifys
          }).then(response => {
            this.$message({
              type: 'success',
              message: '修改角色信息成功'
            })
            // 角色修改成功后清除表单输入框内容
            this.permission.name = ''
            // 关闭dialog框
            this.dialogVisible = false
            this.selectClassifyPermissions()
          })
        })
      }
    },
    // 取消dialog框
    cancelRole() {
      // 关闭dialog框
      this.dialogVisible = false
      // 取消弹框后 清除 表单内容
      this.permission.name = ''
      this.permission.instructions = ''
      this.permission.roles = ''
      this.classify = ''
      this.perId = ''
      for (let i = 0; i < this.classifys.length; i++) {
        // console.log(this.classifys[i].has_many_details);
        for (let j = 0; j < this.classifys[i].has_many_details.length; j++) {
          // console.log(this.classifys[i].has_many_details[j].has_details.explain);
          this.classifys[i].has_many_details[j].checked = false
        }
      }
    },
    // 权限编辑
    handleEdit($index, row) {
      this.dialogType = '编辑权限'
      this.dialogVisible = true
      // console.log("编辑权限");
      // console.log(this.perList);
      // 将当前行的id 赋值给perId 后续修改传值id
      this.perId = row.id
      this.permission.name = row.name
      // console.log("perArr");
      // console.log(row.perArr);
      // console.log(this.perList);
      const arr = row.perArr
      // this.checkedList = row.perArr;
      // console.log("arr");
      // console.log(arr);
      // 循环分类
      for (let i = 0; i < this.classifys.length; i++) {
        // console.log(this.perList[i]);
        // this.perList[i].checked = true;
        // 循环分类的权限名称

        for (let s = 0; s < this.classifys[i].classify_has_many.length; s++) {
          this.classifys[i].classify_has_many[s].checked = false;
          var details_checked = 0;
          for (let j = 0; j < this.classifys[i].classify_has_many[s].has_many_details.length; j++) {
            // 循环当前角色拥有的权限
            for (let k = 0; k < arr.length; k++) {
              if (
                arr[k] == this.classifys[i].classify_has_many[s].has_many_details[j].has_details.explain
              ) {
                this.classifys[i].classify_has_many[s].has_many_details[j].checked = true
                details_checked++;
              }
            }
          }

          if (this.classifys[i].classify_has_many[s].has_many_details.length == details_checked&&details_checked>0) {
            this.classifys[i].classify_has_many[s].checked = true
          } else {
            this.classifys[i].classify_has_many[s].checked = false
          }
        }
      }
      // console.log(this.perList);
      // console.log("1222");
      // console.log(this.checkedAllList);
      // this.perList = row.perArr;
    },
    // 权限删除
    handleDelete($index, row) {
      // console.log("row");
      // console.log(row.id);
      this.$confirm('确认删除?', '警告', {
        configButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warring'
      }).then(() => {
        new Promise((resolve, reject) => {
          deleteClassifyPermissions({ id: row.id }).then(response => {
            this.selectClassifyPermissions()
          })
        })
      })
    },
    // 获取当前用户的登录信息
    getUserInfo() {
      new Promise((resolve, reject) => {
        getInfo().then(response => {
          // console.log("info");
          // console.log(response.data);
          // this.username = response.data.name; //当前登录用户的姓名
          this.userPermissions = response.data.per // 当前登录用户权限数组
          // console.log(this.userPermissions);
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
  .label_per ul {
    width: 520px;
    height: auto;
    list-style: none;
    padding: 0px;
  }
  // .label_per ul li {
  //   width: 120px;
  //   height: 40px;
  //   float: left;
  // }
}
</style>
